from typing import Union
# 1.导入fastAPI模块
from fastapi import FastAPI, Query
from pydantic import BaseModel

# 2.FastAPI对象创建（实例化）
app = FastAPI(
    title="用户管理系统",
    description="用户管理系统接口文档",
    version="1.0.0")


# 3.创建路由函数
# @app.get("路由地址")--- 路由函数的装饰器
# async def index(): ---异步 路由函数
# async --- 异步
@app.get("/", tags=["根路由"])  # 根路由地址
async def index():
    return {"message": "Hello World"}


@app.get("/userinfo/{username}/{id}", tags=["用户信息查询路由"])
async def userInfo(username: str, id: int, age: int):
    name = "当前用户名是：" + username
    userid = "当前用户名的id是：" + str(id)
    useAge = "当前用户名的年龄是：" + str(age)
    return {
        "message": "用户信息",
        "username": name,
        "id": userid,
        "age": useAge
    }


@app.post("/list", summary="用户列表信息添加路由", tags=["用户列表信息添加路由"])
async def userList(age: int, sex: Union[int, None] = 1):
    # async def userList(age: int, sex: int):
    print("性别：", sex, type(sex))
    print("年龄：", age)
    return {"message": "用户列表信息"}


@app.put("/update", tags=["用户更新路由"])
async def updateInfo():
    return {"message": "更新用户信息信息"}


@app.delete("/delete", tags=["用户删除路由"])
async def deleteInfo():
    return {"message": "删除用户信息信息"}


@app.post("/register", summary="用户注册接口")
def login(username: str = Query(max_length=12, min_length=6),
          password: str = Query(default="123456", max_length=6)):
    try:
        print("用户名：", username)
        print("密码：", password)

        return {
            "code": 200,
            "message": "注册成功",
            "data": {
                "username": username,
                "password": password
            }
        }
    except Exception as e:
        return {
            "code": 500,
            "message": "服务器异常……",
        }


# 请求数据模型
class LoginData(BaseModel):
    username: str
    password: str
    token: str | None = None


# 响应数据模型
class LoginResponseData(BaseModel):
    code: int
    message: str
    data: dict | None = None


@app.post("/login", summary="用户登录接口", response_model=LoginResponseData)
def login(login_data: LoginData):
    try:
        if login_data.username == "admin" and login_data.password == "123456":
            return LoginResponseData(  # 使用模型构造返回数据
                code=200,
                # message="登录成功",
                # token="ferwerwerwerwe",
                data={
                    "username": login_data.username,
                }

            )

        else:
            return LoginResponseData(
                code=400,
                message="用户名或密码不正确，登录失败",
                data=None
            )

    except Exception as e:
        return LoginResponseData(
            code=500,
            message="服务器异常……",
            data=None
        )


# 需求：创建用户登录接口，
# 1.接收参数有用户名和密码
# 2.模拟数据库查询用户名admin和密码123456，判断用户是否登录成功
# 3.登录成功返回用户信息，登录失败返回错误信息
# 返回数据的格式：
# {
# "code": 200,
# "message": "登录成功",
# "data": {
# "username": "admin",
# "token": "ferwerwerwerwe"
#
# }
# }
# 4.使用try...except...处理异常

# 4.启动fastAPI服务
if __name__ == '__main__':
    # 导入ASGI服务器模块
    import uvicorn

    # uvicorn.run(当前应用对象, host="域名地址", port=端口号)
    uvicorn.run(app, host="127.0.0.1", port=8000)
